<template>
    <el-row :gutter="20">
        <el-col v-if="list" :span="Template.allowBestFitColumns!==2||list.StatusCode<=0||!list.StatusCode?24:18">
            <div v-if="data">
                <el-form v-if="data.formSet" ref="ruleFormRef" :model="list" :rules="data.formSet.rules" :size="data.formSet.size" :label-width="data.formSet.labelWidth" >
                    <div style="margin-bottom: 20px;">
                        <el-button style="margin-right: 10px;" :size="data.formSet.size" type="success" @click="saveForm(ruleFormRef)">保存</el-button>
                        <el-button style="margin-right: 10px;" :size="data.formSet.size" type="success" v-if="(list.StatusCode===0||DataSource.StatusCode==0)&&Template.allowBestFitColumns===2" @click="addTask()">提交</el-button>
                        <el-dropdown style="margin-right: 10px;" v-if="(list.StatusCode===0||DataSource.StatusCode==0)" :size="data.formSet.size" v-for="(items,key) in ManualActRules">
                            <el-button type="primary">{{key}}<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-for="(item,index) in items" v-show="item.isExtFlow===0||(item.isExtFlow===1&&![1,2,8].includes(list.StatusCode))" @click="runActRules(item)">{{item.ruleName}}</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-dropdown style="margin-right: 10px;" :size="data.formSet.size" v-if="printTemplates.length>0">
                            <el-button type="primary">打印<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-if="printTemplates.length>0" v-for="item in printTemplates" @click="handlePrint(item)" >{{ item.name }}</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                    <el-row>
                        <template v-for="(item,index) in data.formData.mainList" :key="index">
                            <el-col :span="item.span" v-if="item.show">
                                <el-form-item :label="item.name" v-if="item.type===0" :required="item.required" :prop="item.required?item.value:''">
                                    <el-input v-if="item.componentType=='text'" @change="ValueChange(list,data.formData.mainList,item.value,data.formData.tableName)" type="text" v-model="list[item.value]" :disabled="item.permission?true:false" />
                                    <el-input v-else-if="item.componentType=='textarea'" @change="ValueChange(list,data.formData.mainList,item.value,data.formData.tableName)" v-model="list[item.value]" type="textarea" :disabled="item.permission?true:false" />
                                    <el-input v-else-if="item.componentType=='automaticText'" @change="ValueChange(list,data.formData.mainList,item.value,data.formData.tableName)" v-model="list[item.value]" type="text" placeholder="自动编号" :disabled="item.permission?true:false" />
                                    <el-input v-else-if="item.componentType=='list'" @change="ValueChange(list,data.formData.mainList,item.value,data.formData.tableName)" v-model="list[item.value]" :disabled="item.permission?true:false" >
                                        <template #append><el-icon @click="listClick(item.items,item)"><Plus /></el-icon></template>
                                    </el-input>
                                    <el-date-picker
                                        v-else-if="item.componentType=='date'"
                                        type="date"
                                        placeholder="请选择"
                                        :disabled="item.permission?true:false"
                                        v-model="list[item.value]"
                                    />
                                    <el-select v-else-if="item.componentType=='down'&&item.Downoption!='selection'" @change="ValueChange(list,data.formData.mainList,item.value,data.formData.tableName)" class="m-2" v-model="list[item.value]" :disabled="item.permission?true:false" placeholder="请选择">
                                        <el-option
                                            v-for="item in item.items"
                                            :key="item.combItemID"
                                            :label="item.value"
                                            :value="item.combItemID"
                                            />
                                    </el-select>
                                    <sx-select v-else-if="item.componentType=='down'&&item.Downoption=='selection'" :opitonList="item.items" :model="list[item.value]" :permission="item.permission" :name="item.value" @elselect="elselect"></sx-select>
                                    <el-input  v-else-if="item.componentType=='accessory'" readonly placeholder="请选择文件" :value="valueData(list,item.value)" @change="ValueChange(list,data.formData.mainList,item.value,data.formData.tableName)">
                                        <template #append><el-icon @click="showFiles({item:item ,value:list[item.value],target:list,ref:ruleFormRef,multiple:true,fileType:'files',id:data.formData.tableId})"><Plus /></el-icon></template>
                                    </el-input>
                                </el-form-item>
                                <div v-if="item.componentType=='lable'" :style="{padding:'5px '+data.formSet.labelWidth/2+'px',width:'100%',textAlign:item.direction?item.direction:'left',fontSize:item.size?item.size+'px':''}">
                                        {{item.title}}
                                </div>
                            </el-col>
                            <el-col v-if="item.lineFeed=='true'" :span="24"></el-col>
                        </template>
                    </el-row>
                </el-form>
                <el-tabs
                        v-model="activeNameTo"
                        type="card"
                        class="demo-tabs"
                    >
                        <el-tab-pane v-for="(item,index) in data.formData.tableList" :label="item.name" :name="index">
                            <vxe-toolbar ref="xToolbar">
                                <template #buttons>
                                <vxe-button size="mini" status="primary" content="新增" @click="addRow(index,item)"></vxe-button>
                                <vxe-button size="mini" status="primary" content="复制" @click="copy(index,item)"></vxe-button>
                                <vxe-button size="mini" status="primary" content="清空" @click="empty(index,item)"></vxe-button>
                                <vxe-button size="mini" status="warning" content="删除" @click="removeRow(index,item)"></vxe-button>
                                </template>
                            </vxe-toolbar>
                            <vxe-table
                            :align="null"
                            border
                            style="width:100%;"
                            keep-source
                            :ref="setItemRef"
                            :size="data.formSet.size"
                            :scroll-x="{enabled: false}"
                            :selectCellByHeader="true"
                            :edit-rules="item.rules"
                            :edit-config="{trigger: 'click', mode: 'cell', showUpdateStatus: true, showInsertStatus: true}"
                            :row-config="{isCurrent: true, isHover: true}"
                            :data="ChildTables?ChildTables[item.value]:[]"
                            :column-config="{resizable: true}"
                            >
                                <vxe-column type="checkbox" width="60"></vxe-column>
                                <vxe-column type="seq" width="60"></vxe-column>
                                <vxe-column style="padding: 10px;" v-for="(element,indexs) in item.column" :visible="element.show" show-overflow :width="element.width"  :key="element.value" :edit-render="{autofocus: '.vxe-input--inner'}" :field="element.value" :title="element.name">
                                    <template #edit="{ row }">
                                        <el-input v-if="element.componentType=='text'"  @change="ValueChange(row,item.column,index,element.value,item.value,'table')" :size="data.formSet.size" type="text" v-model="row[element.value]" :disabled="element.permission?true:false" />
                                        <el-input v-else-if="element.componentType=='textarea'" @change="ValueChange(row,item.column,index,element.value,item.value,'table')" :size="data.formSet.size" v-model="row[element.value]" type="text" :disabled="element.permission?true:false" />
                                        <el-input v-else-if="element.componentType=='automaticText'" @change="ValueChange(row,item.column,index,element.value,item.value,'table')" :size="data.formSet.size" v-model="row[element.value]" type="text" placeholder="自动编号" :disabled="element.permission?true:false" />
                                        <el-input v-else-if="element.componentType=='list'" @change="ValueChange(row,item.column,index,element.value,item.value,'table')" :size="data.formSet.size" v-model="row[element.value]" :disabled="element.permission?true:false" >
                                            <template #append><el-icon @click="listClick(element.items,element,element.value,index,item.value,'table')"><Plus /></el-icon></template>
                                        </el-input>
                                        <el-date-picker
                                                v-else-if="element.componentType=='date'"
                                                type="date"
                                                placeholder="请选择"
                                                :size="data.formSet.size"
                                                :disabled="element.permission?true:false"
                                                v-model="row[element.value]"
                                            />
                                            <vxe-select v-else-if="element.componentType=='down'&&element.Downoption!='selection'" transfer v-model="row[element.value]" placeholder="默认尺寸">
                                                <vxe-option v-for="itemt in element.items" :key="itemt.combItemID" :value="itemt.combItemID" :label="itemt.content"></vxe-option>
                                            </vxe-select>
                                        <sx-select v-else-if="element.componentType=='down'&&element.Downoption=='selection'" :readonly="false" :index="index" :opitonList="element.items" :model="row[element.value]" :permission="element.permission" :isEL="'table'" :name="element.value" @elselect="elselect"></sx-select>
                                        <el-input v-else="element.componentType=='text'" @change="ValueChange(row,item.column,index,element.value,item.value,'table')" :size="data.formSet.size" type="text" v-model="row[element.value]" :disabled="element.permission?true:false" />
                                        <!-- <div>
                                            {{element}}
                                        </div> -->
                                    </template>
                                    <template #default="{ row }" v-if="element.componentType=='down'">
                                        {{element.Downoption=='selection'?elselectData(row[element.value],element.items):elselectData(row[element.value],element.items,'dan')}}
                                    </template>
                                </vxe-column>
                            </vxe-table>
                        </el-tab-pane>
                </el-tabs>
            </div>
        </el-col>
        <el-col :span="Template.allowBestFitColumns==2&&list.StatusCode>0?workFlowWidth:0" style="border: 1px dashed green;padding: 10px;">
            <div style="height: 550px;overflow: auto;">
                <sxPse :data="ApprovalData.task"></sxPse>
            </div>
            <div>
                <vxe-form  v-if="ApprovalData.do"
                    title-colon
                    ref="xForm"
                    title-width="100"
                    :data="ApprovalData"
                    :rules="ApprovalRules"
                    @submit="flowtodo">
      
                  <vxe-form-item field="status" span="24" :item-render="{}" v-if="ApprovalData.task[ApprovalData.level].nodeName!=='退回发起人'">
                      <template #default="{ data }">
                        <vxe-radio-group v-model="data.status" @click="approstatus">
                          <vxe-radio :label="8" content="同意"></vxe-radio>
                          <vxe-radio :label="7" content="退回"></vxe-radio>
                          <vxe-radio :label="9" content="拒绝"></vxe-radio>
                        </vxe-radio-group>
                      </template>
                    </vxe-form-item>
                  <vxe-form-item field="opinion" span="24" :item-render="{}" v-if="ApprovalData.task[ApprovalData.level].nodeName!=='退回发起人'">
                  <template #default="{ data }">
                    <vxe-textarea v-model="data.opinion" placeholder="请输入审批意见" :autosize="{minRows: 3, maxRows: 3}" clearable></vxe-textarea>
                  </template>
                </vxe-form-item>
                  <vxe-form-item align="center" span="24">
                    <template #default="{ data }">
                      <vxe-button status="primary" v-if="data.status===8" @click="addproc()" content="加签"></vxe-button>
                      <vxe-button type="submit" status="primary" content="提交"></vxe-button>
                      <vxe-button type="reset" content="重置"></vxe-button>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </div>
        </el-col>
    </el-row>
    <organization ref="Organization" @selectUser="addsign"></organization>
    <FilesSelect ref="SXFiles" @submit="getFilesData"></FilesSelect>
    <prints ref="Print"></prints>
    <!-- 列表弹窗 -->
    <el-dialog v-model="dialogVisible" :title="'数据选择列表 --- '+title" width="1200" >
        <div style="display: flex;align-items: center;">
            <el-input size="small" style="width: 300px;">
                <template #append><div>全新搜索</div></template>
            </el-input>
            <el-checkbox style="margin-left: 10px;"  label="高级搜索" size="small" />
        </div>
        <div style="margin-top: 5px; border:1px solid #0000001d;" >
            <el-table
                border
                :data="tableList.list"
                size="small"
                ref="reference"
                height="400"
                @selection-change="handleSelectionChange"
                @row-dblclick="handleAddRow"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column v-for="item in tableList.field" :show-overflow-tooltip="true" :property="item.fieldDispName" :label="item.fieldDispName" />
            </el-table>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-top: 5px;">
            <div>
                <el-button size="small" @click="AddBoxList">添加</el-button>
                <el-button size="small" @click="removeBoxlist">删除</el-button>
            </div>
            <el-pagination
                v-if="!loading"
                :small="true"
                v-model:current-page="page.pageNum"
                v-model:page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <div style="margin-top: 5px; border:1px solid #0000001d;" >
            <el-table
                v-if="!loading"
                border
                :data="boxList"
                size="small"
                height="200"
                @selection-change="handleSelectionChange2"
                @row-dblclick="handleDeleteRow"
            >
            <el-table-column type="selection" width="55" />
            <el-table-column v-for="item in tableList.field" :show-overflow-tooltip="true" :property="item.fieldDispName" :label="item.fieldDispName" />
            </el-table>
        </div>
        <template #footer>
            <span class="dialog-footer">
              <el-button size="small" @click="dialogVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="save">
                确定
              </el-button>
            </span>
          </template>
    </el-dialog>
  <DataGridSelect ref="DGE" :isequipment="isequipment" @submit="getSourceData"></DataGridSelect>

</template>
<script setup>
    import DataGridSelect from './select.vue'
    import {ref,watch,reactive,getCurrentInstance,onMounted} from "vue"
    import {getDataGrid,getDefault,getSelectRule,} from "/@/api/linkoo/form/index.ts"
    import { ElMessage } from 'element-plus'
    import XEUtils from 'xe-utils'
    import VXETable from "vxe-table"
    import {editForm} from "/@/api/linkoo/form"
    import {useRoute, useRouter} from 'vue-router'
    import {mathAll} from "/@/utils/mathji"
    import sxPse from "./sxpse.vue"
    import {getWorkFlowData,flowTodo} from "/@/api/linkoo/workflow";
    import {getPrintList} from "/@/api/linkoo/print";
    import prints from "/@/views/linkoo/print/prints.vue"
    import organization from './organization.vue'
    import FilesSelect from "./FilesSelect.vue"
    import sxSelect from "./sxSelect.vue"
    let SXFiles = ref(null)
    let list = ref({})
    const {proxy} = getCurrentInstance()
    let workFlowWidth = ref(6)
    let ruleFormRef = ref(null)
    let ApprovalData=ref({task:[]}) 
    let ApprovalRules=ref({})
    let isTable = ref(null)
    let activeNameTo = ref(0)
    let reference = ref(null)
    let DGE = ref(null)
    let dialogVisible =ref(false)
    let loading = ref(true)
    let Print = ref()
    let page=ref({
        pageNum:1,
        pageSize:10,
        total:0
    })
    const route =useRoute()
    let router = useRouter()
    let xuanlits = ref(null)
    let checkboxList = ref([])
    let xID = ref(null)
    let ChildTables = ref(null)
    const props = defineProps({
        Template:{
            type:Object,
            required:true
        },
        DataSource:{
            type:Object,
            required:true
        },
        ActRules:{
            type:Object,
            required:true
        },
        Fields:{
            type:Object,
            required:true
        },
        isNew:{
            type:Boolean,
            required:false
        },
        Combo:{
            type:Object,
            required:false
        }
    })
    let DFV=ref({})
    let data = ref(null)
    let Zlist = ref({})
    let Organization = ref()
    onMounted(()=>{
        setTimeout(()=>{
            XEUtils.objectEach(props.DataSource,(item,key)=>{
                if(key!=='ChildTables'){
                    list.value[key]=item
                    Zlist.value[key]=item
                }
            })
            ChildTables.value=props.DataSource.ChildTables
            data.value=props.Template.FormCode
            dfvset(props.DataSource.RecordID)
        },1000)
    })
    let ManualActRules = ref({})
    let printTemplates = ref([])
    const elselectData = (value,op,dan)=>{
        
        let str ='';
        if(value){
            if(dan){
                op.forEach((items)=>{console.log(value,items.combItemID,op,dan);
                    if(value==items.combItemID){
                        str=items.value
                        
                    }
                })
            }else{
                value.split(",").forEach((item)=>{
                    op.forEach((items)=>{
                        if(item==items.combItemID){
                            if(str==''){
                                str=items.value
                            }else{
                                str=str+','+items.value
                            }
                            
                        }
                    })
                })
            }
            
        }
        return str
    }
    const dfvset = (items)=>{
            console.log(data.value);
            if(props.Template.allowBestFitColumns===2&&list.value.StatusCode>0){
                GetWF()
            }
            if(props.isNew){
                getDefaults(list.value,data.value.formData.tableId)
            }
            getPrintList({tid:props.Template.templateID}).then(res=>{
                 //   console.log(res);
                    if(res.data.list&&res.data.list.length>0){
                        printTemplates.value=res.data.list
                    }
                })
            data.value.formData.tableList.forEach((item,indexs)=>{
                DFV.value[item.value]={RecordID: items, Seq: null, Extend: '{}'}
            }) 
            XEUtils.objectEach(props.ActRules, async (items, key) => {
                let rules = XEUtils.filter(items, item => item.runTime.split(',').includes('999'))
                if (rules.length > 0) {
                    ManualActRules.value[key] = rules
                }
            })  
    }
    let showedit = ref(false)
    let wkeditls = ref(false)
    let wkedit = ref(false)
    const GetWF=()=>{
        getWorkFlowData(props.Template.templateCode,list.value.RecordID).then((res)=>{
            if (res.data.task!==undefined&&res.data.task!==''){
                console.log(res);
                ApprovalData.value=res.data
                const extend=res.data.task[res.data.level]?res.data.task[res.data.level].extend:{}
                if(((extend.editor!==undefined&&extend.editor.length>0)||extend.fieldstatus===1)&&res.data.do){
                    showedit.value=true
                    wkeditls.value=true
                    wkedit.value=false
                    if(extend.fieldstatus===0&&extend.editor.length>0){
                        const t=[],f =[]
                        XEUtils.arrayEach(extend.editor,item=>{
                            const k=item.split(".")
                            t.push(k[0])
                            f.push(k[1])
                        })

                        XEUtils.objectEach( props.Fields, (item, key) => {
                            item.map(it=>{
                            it.editable=0;
                            if(t.includes(key)&&f.includes(it.fieldName)){
                                it.editable=1
                            }

                            return it})
                        })
                    }
                }
            }
        })
    }
    const itemRefs = ref([])
    const setItemRef = el => {
        if (el) {
            itemRefs.value.push(el)
        }
    }
    watch(()=>{return dialogVisible.value},(val,olv)=>{
        if(!val){
            loading.value=true
            page.value={pageNum:1,pageSize:10,total:0}
            tableList.value=null
            xuanlits.value = null
        }
    })
    
    
    
    const getDefaults = (all,id)=>{
       // console.log("234567890",id);
        getDefault(id).then((res)=>{
            XEUtils.objectEach(res.data, (item, key) => {
                console.log(res.data);
                all[key] = item
            })
            if (id === data.value.formData.tableID) {
                all['StatusCode'] = 0
            }
        })
    }
    let opinion=ref({8:'同意',7:'退回',9:'拒绝'})
    let tableList = ref({list:[],field:[]})
    let Xitem = ref(null)
    let Xrule = ref(null)
    let sunTable = ref(null)
    let SXval = ref(null)
    let title = ref(null)
    let boxList = ref([])
    const listClick = (val,item,isT,sun,Xt)=>{
        console.log(val,item,isT,sun,Xt);
        // if(item.componentFieldName==""){
        //     ElMessage({
        //         type: 'info',
        //         message: `请完善扩展属性 ! !`,
        //     })
        //     return
        // }
      xID.value=val
      getList()

        Xitem.value=item
      Xrule.value = item.configList
      title.value=item.name
        if(isT==='table'){
            isTable.value=isT
            sunTable.value = sun
            SXval.value=Xt
        }

    //
    // }
    // const showSource = async ({item, value, target, ref}) => {
      return;
      console.log(item, value, target, ref);
      if(state.statusCode!==0)return
      if (item.FilterExpr !== '' && item.componentType === 'list') {
        if (state.filters[item.fieldName]===undefined){
          state.filters[item.fieldName]=XEUtils.clone(item.componentFilterExpr, true)
        }
        let filter = XEUtils.clone( state.filters[item.fieldName], true)
        const regex = /({(\S+)})/gis
        let m
        let keys = [], vals = []
        while ((m = regex.exec(filter)) !== null) {
          // 这对于避免零宽度匹配的无限循环是必要的
          if (m.index === regex.lastIndex) {
            regex.lastIndex++
          }
          // 结果可以通过`m变量`访问。
          m.forEach((match, groupIndex) => {
            if (groupIndex === 1) {
              keys.push(match)
            }
            if (groupIndex === 2) {
              vals.push(match)
            }
          })
        }
        XEUtils.arrayEach(keys, (it, key) => {
          //   // 主字段查找
          let val = XEUtils.get(state.formData, vals[key], '')
          if (val === '') {
            //     // 明细表行数据查找
            val = XEUtils.get(target, vals[key], '')
          }
          if (filter.indexOf(' in ') > 1) {
            const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[ref].getTableData().fullData, true), vals[key])
            // console.log(data,'dddddd')
            let vv=data?data.join("','"):''
            filter = filter.replace(it, `'${vv}'`)
          }else{
            filter = filter.replace(it, val)
          }
        })

        item.componentFilterExpr = filter
      }
      DGE.value.Data = Object.assign({}, {field: item, value: value, data: state.formData})
      DGE.value.todo()
      DGE.value.keyword=''
      // this.$refs.DGE.showDialog = true
      state.selectDataGridTarget = {field: item, target: target, ref: ref}
    }



    const getList = ()=>{
        loading.value=true
        getDataGrid({id:xID.value.id,tid:xID.value.tid,pageNum:page.value.pageNum,pageSize:page.value.pageSize}).then((res)=>{
            console.log(res);
            if(res.code===0){
                tableList.value=res.data
                page.value.total=res.data.total
                loading.value=false
              dialogVisible.value=true
            }
        })
    }
    const handleCurrentChange = (val)=>{
        console.log(val);
        getList()
    }
    const handleSizeChange = (val)=>{
        console.log(val,page.value);
        getList()
    }
    const handleSelectionChange = (val)=>{
        checkboxList.value=val
    }
    let checkboxList2 = ref([])
    const handleSelectionChange2 = (val)=>{
        checkboxList2.value=val
    }
    const handleAddRow = (val)=>{
        checkboxList2.value=val
    }
    const handleDeleteRow = (val)=>{
        checkboxList2.value=val
    }
    const removeBoxlist =()=>{
        if(checkboxList2.value.length==0){
            ElMessage({
                type: 'info',
                message: `请选择后删除 ! !`,
            })
            return
        }
        checkboxList2.value.forEach((item,index)=>{
            boxList.value.forEach((elem,sun)=>{
                if(item==elem){
                    boxList.value.splice(sun,1)
                    checkboxList.value.splice(sun,1)
                }
            })
            
        })
    }
    const AddBoxList = ()=>{
        if(checkboxList.value.length==0){
            ElMessage({
                type: 'info',
                message: `请选择后添加 ! !`,
            })
            return
        }
        boxList.value=XEUtils.uniq([...boxList.value,...checkboxList.value])
    }
    const save = ()=>{
        let str ;
        let isTy=false
        XEUtils.objectEach(Xrule.value,(item,key)=>{
            str= []
            checkboxList.value.forEach(element => {
                console.log(element,item);
                if(element[item.v]){
                    str.push(element[item.v])
                }else{
                    isTy=true
                }
            });
        })
        if(isTy){
            ElMessage({
                type: 'info',
                message: `未能成功取值，请检查 ! !`,
            })
            dialogVisible.value=false
            return
        }
        if(isTable!="table"){
            list.value[Xitem.value.value]=str.toString()
            tableList.value = null
            Xitem.value = null
            Xrule.value = null
        }else{
            console.log(list.value.ChildTables[SXval.value][sunTable.value][Xitem.value.value],str.toString());
        }
        dialogVisible.value=false
    }
    const addRow = async(index,item)=>{
        const newRecord = {}
        const { row: newRow } = await itemRefs.value[index].insert(newRecord)
    }
    const removeRow = async (index,item) => {
        let isXR = itemRefs.value[index].getCheckboxRecords()
        if(isXR.length==0){
            ElMessage({
                type: 'info',
                message: `未选择需要删除的数据 ! !`,
            })
            return
        }
              const type = await VXETable.modal.confirm('您确定要删除选中的数据?')
              if (type !== 'confirm') {
                return
              }
              itemRefs.value[index].remove(isXR)
    }
    // 复制
    const copy = (index,item)=>{
        let isXR = itemRefs.value[index].getCheckboxRecords()
        console.log(index,item,isXR);
        if(isXR.length==0){
            ElMessage({
                type: 'info',
                message: `未选择需要复制的数据 ! !`,
            })
            return
        }
        isXR.forEach((items)=>{
            delete items['_X_ROW_KEY']
            itemRefs.value[index].insert(items)
        })
    }
    const empty = async(index,item) =>{
        const type = await VXETable.modal.confirm('您确定要请空数据?')
         if (type !== 'confirm') {
           return
         }
         itemRefs.value[index].remove()
    }
    const saveForm = async(formEl)=>{
        if (!formEl) return
        await formEl.validate(async (valid,fields)=>{
            if(valid){
                console.log(itemRefs.value[0].getRecordset());
                let sdata = {}
                sdata['T']=props.Template.templateID
                sdata['M']=getMainForm(route.params.id)
                sdata['D']=getTables()
                await editForm(route.params.templateCode, route.params.id,sdata ).then((res)=>{
                    if(res.code === 0){
                        ElMessage.success('单据操作成功')
                        const url = '/form/edit/' + route.params.templateCode + "/" + res.data.id
                        router.push(url)
                    }
                })
            }else{
                console.log('error submit!', fields)
            }
        })
        console.log(route.params.templateCode, route.params.id,list.value);
    }
    const getMainForm=(id)=>{
        let obj = {}
        obj[data.value.formData.tableName]={}
        if(id==0){
            XEUtils.objectEach(list.value,(item,key)=>{
                if(key!=='ChildTables'){
                    console.log(obj);
                    obj[data.value.formData.tableName][key]=item
                }
            })
        }else{
            XEUtils.objectEach(list.value,(item,key)=>{
                if(Zlist.value[key]!=list.value[key]||(key === 'Extend')){
                    obj[data.value.formData.tableName][key]=item
                    console.log(obj);
                }
            })
        }
        return obj
    }
    const getTables=()=>{
        let obj = {}
        itemRefs.value.forEach((item,index)=>{
            let add = item.getRecordset().insertRecords
            let remove = item.getRecordset().removeRecords
            let updata = item.getRecordset().updateRecords
            
                if(data.value.formData.tableList[index]){
                    obj[data.value.formData.tableList[index].value]={
                        DA:add,
                        DD:remove,
                        DE:updata
                    }
                }
            
        })
        console.log(obj);
        return obj
    }
    const ValueChange=async(data, fields,index, fieldName,firld,isTable,duanxuan )=>{
        let source = XEUtils.clone(data, true)
        source = XEUtils.objectMap(source, item => item === null ? 0 : item)
        XEUtils.objectEach(fields,async(item,index)=>{
            if(item.calculation){
                let st = item.setCalculation.split(' ')
                if(isTable=="table"){
                    await getDFSum(index,st,item)
                }else{
                    list.value[item.value]= await getFTsum(st,list.value)
                }
            }
        })
        setTimeout(async ()=>{
            XEUtils.objectEach(props.ActRules,async (items)=>{
                let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('106') && XEUtils.includes(item['onChangeFileld'].split(','), fieldName))
                console.log(selectrules);
                for (let i = 0; i < selectrules.length; i++) {
                    await loadSelectRules(selectrules[i],index)
                }
            })
        },200)
    }
    const loadSelectRules = async (rule,index)=>{
        ElMessage.info('开始执行取数....')
        if (rule.ruleName === '合计'){
            const r = XEUtils.toStringJSON(rule.targetField)
            r.forEach(row => {
                const t = row.tofield.split('.')
                const f = row.field.split('.')
                if (t[0] === data.value.formData.tableName){

                }
                return
            })
        }
        let filterExpr = rule.filterExpr
        const regex = /({([a-zA-Z\d]+)[.]([a-zA-Z\d]+)})/gis
        let m
        let keys = [], table = [], vals = []
        while ((m = regex.exec(filterExpr)) !== null) {
            // 这对于避免零宽度匹配的无限循环是必要的
            if (m.index === regex.lastIndex) {
            regex.lastIndex++
            }
            m.forEach((match, groupIndex) => {
            if (groupIndex === 1) {
                keys.push(match)
            }
            if (groupIndex === 2) {
                table.push(match)
            }
            if (groupIndex === 3) {
                vals.push(match)
            }
            })
        }
        XEUtils.arrayEach(keys, (it, key) => {
            if (table[key] !== data.value.formData.tableName && filterExpr.indexOf(' in ') > 1) {
                const data = XEUtils.pluck(XEUtils.clone(itemRefs.value[index].getTableData().fullData, true), vals[key])
                filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
            }else{
                console.log(list.value,vals[key]);
                let val = XEUtils.get(list.value, vals[key], '')
                if (val === ''&&itemRefs.value[index]!==undefined) {
                    const data = itemRefs.value[index].getCurrentRecord()
                    val = XEUtils.get(data, vals[key], "")
                }
                console.log(val,'++++',it);
                filterExpr = filterExpr.replace(it, val)
            }
        })
        console.log(rule);
        await GetSelectRules(rule, filterExpr,index)
    }
    const GetSelectRules = async(rule, filterExpr,sun)=>{
        console.log(rule.ruleID, filterExpr);
        await getSelectRule(rule.ruleID, filterExpr).then(res => {
            if (res.data.list) {
                fromSelectRule(rule, res.data.list,sun)
                ElMessage.success('成功执行[' + rule.ruleName + '],数据已添加')
            } else {
                ElMessage({type: 'info', message: '成功执行[' + rule.ruleName + '],但未到取到数据',})
            }
        })
    }
    const fromSelectRule = (rule, datat,sun)=>{
        console.log(rule, datat,sun);
        if (datat === null) return
        const topull = JSON.parse(rule['targetField'])
        let TB = {}, link = false, linkstr = ''
        topull.forEach(row => {
            const tf = row['tofield'].split('.')
            if (TB[tf[0]] === undefined) TB[tf[0]] = {}
                TB[tf[0]][tf[1]] = row['field'].indexOf('.') > -1 ? row['field'].split('.')[1] : row['field']
            if (row.type === 'keys') {
                link = true
                linkstr = tf[1]
            }
        })
        XEUtils.objectEach(TB, async (fields, key) => {
            if (key === data.value.formData.tableName) {
                XEUtils.objectEach(fields, (f, t) => {
                    list.value[t] = datat[0][f]
                })
            }else{
                console.log(ChildTables.value,key);
                const $tb = itemRefs.value[sun]
                let records = []
                for (let i=0;i<datat.length;i++){

                    const record = await getDTdefault(key)
                    XEUtils.objectEach(fields, (f, t) => {
                        record[t] = datat[i][f]
                    })
                    records.push(record)
                }
                console.log(records);
                if (rule.clearAllRow === 1) {
                    $tb.remove()
                }
                if (link) {
                    const $tb = itemRefs.value[sun]
                    let dd =  $tb.getTableData().visibleData
                    XEUtils.mapTree(dd, item => {
                        console.log(item);
                        const record = XEUtils.find(records, r => r[linkstr] === item[linkstr])
                        if (record) {
                            XEUtils.objectEach(record, (it, key) => {
                            if(it){
                                item[key] = it
                            }

                            })
                        }
                        XEUtils.objectEach(data.value.formData.mainList[key], async (field) => {
                            if (field.componentType === 9 && field.componentFieldName !== '') {
                            const jgm = mathAll(field.componentFieldName, item)
                            item[field.value] = jgm ? XEUtils.toFixed(jgm, field.fieldPrecision) : jgm
                            }
                        })
                        return item
                    })
                    // console.log(dd);
                    $tb.updateData(dd)
                }else{
                    if($tb.treeConfig){
                        records=XEUtils.toArrayTree(records,{parentKey:$tb.treeConfig.parentField,key:$tb.treeConfig.rowField})
                        records=XEUtils.toTreeArray(records,{clear:true})
                        for(let i=0;i<records.length;i++){
                            await $tb.insertAt(records[i])
                        }
                    }else{
                        $tb.insertAt(records,-1)
                    }
                }
            }
        })
    }
    const getDTdefault = async (table,news) => {
        const row = DFV.value[table]
        const tb = XEUtils.find(data.value.formData.tableList, item => item.value === table)
        if(tb.allowWorkFlow>0){
            await getDefault(tb.tableID).then(res => {
            XEUtils.objectEach(res.data, (item, key) => {
                console.log(key);
                row[key] = item
            })
            })
        }
      return XEUtils.clone(row)
    }
    const getFTsum = async(st,model)=>{
        let str=''
        await st.forEach((item,index)=>{
            if(XEUtils.isInteger(index/2)){
                if(model[item]){
                    str=str+model[item]
                }else{
                    str=str+'0'
                }
                
            }else{
                str=str+item
            }
        })
        return mathAll(str)
    }
    const getDFSum =async(index,st,val)=>{
        const $tb = itemRefs.value[index]
        const tb = $tb.getTableData().tableData
        tb.forEach((itemt,sun)=>{
            let str=''
            st.forEach((item,indexs)=>{
                if(XEUtils.isInteger(indexs/2)){
                    if(itemt[item]){
                        str=str+itemt[item]
                    }else{
                        str=str+'0'
                    }
                }else{
                    str=str+item
                }
            })
            itemt[val.value]=mathAll(str)
        })
    }
    const addTask = ()=>{
        if(list.value.RecordID===0||!list.value.RecordID){
            ElMessage.error('请先保存后再提交')
            return
        }
        flowTodo(route.params.templateCode,route.params.id, 0, {}).then(res=>{
            list.value.StatusCode=1
            GetWF()
        })
    }
    const addproc = ()=>{
        Organization.value.showDialog()
    }
    const addsign = (users)=>{
        const data=XEUtils.clone(ApprovalData.value)
        if(users.length>0&&data.status===8){
            data['addsign']=users.map(user=>{
                return {id:user.id,name:user.userName,pid:"d"+user.deptId,types:"u"}
            })
            flowTodo(route.params.templateCode,route.params.id, ApprovalData.value.tid,data).then(res=>{
                proxy.mittBus.emit('onCurrentContextmenuClick', { contextMenuClickId: 0, ...route });
            })
        }
    }
    const flowtodo = ()=>{
        const data=XEUtils.clone(ApprovalData.value)
          if(data.task[data.level].nodeName==='退回发起人'){
            data.status=8
            data.opinion="重新提交"
          }
        flowTodo(route.params.templateCode,route.params.id, ApprovalData.value.tid,data).then(res=>{
            proxy.mittBus.emit('onCurrentContextmenuClick', { contextMenuClickId: 0, ...route });
        })
    }
    const approstatus = ()=>{
        setTimeout(()=>{
          ApprovalData.value.opinion=opinion.value[ApprovalData.value.status]
        },10)
    }
    const runActRules = (rule) => {
      ElMessage.success('执行程序中....'+rule.ruleName)
      switch (rule.ruleType) {
        case 1:
          loadSelectRules(rule)
          break
        case 2:
          runUpdateRule(rule)
          break
        case 3:
          runPostRule(rule)
          break
      }
    }
    const handlePrint  = async(item) => {
      const datat={printData:item,rid:list.value.RecordID,Combo:props.Combo,data:data.value,model:{...list.value,table:ChildTables.value}}
      Print.value.Load(0,datat)
    }
    const getextend = (data,item)=>{
        console.log(data,item);
    }
    let selectFiels = ref(null)
    let listF = ref(null)
    const showFiles = ({item, value, target, ref, multiple, fileType,id})=>{
        console.log({item, value, target, ref, multiple, fileType});
        SXFiles.value.Data = Object.assign({}, {field: item, value: value})
        SXFiles.value.dataTypeID = id
        SXFiles.value.todo()
        SXFiles.value.multiple = multiple
        SXFiles.value.fileType = fileType
        SXFiles.value.title = fileType === 'images' ? '图片选择' : '附件选择'
        SXFiles.value.status =list.value.StatusCode
        SXFiles.value.fileSize =8 
        selectFiels.value = item
        listF.value=target
    }
    const getFilesData = ({data, filesName, extdata})=>{
        console.log(data, filesName, extdata);
        listF.value['Extend']={[selectFiels.value.value]: filesName}
        let extend = XEUtils.toStringJSON(listF.value['Extend'])
        listF.value[selectFiels.value.value] = data
        if (extdata.length > 0) {
            const field = JSON.parse(selectFiels.value.value)
            for (let i = 0; i < extdata.length; i++) {
                if (i === 0) {
                    XEUtils.objectEach(field, (item, key) => {
                        listF.value['Extend'][key] = extdata[0][item]
                    })
                }else {
                    let rows = {}, ext = {}
                    rows[state.selectFiels.field.fieldName] = data
                    ext[state.selectFiels.field.fieldName] = filesName
                    rows['Extend'] = XEUtils.toJSONString(ext)
                    XEUtils.objectEach(field, (item, key) => {
                        rows[key] = extdata[i][item]
                    })
                    // this.$refs[state.selectFiels.ref][0].insertAt(rows,-1)
                }
            }
        }
        listF.value['Extend'] = XEUtils.toJSONString(extend)
        console.log(listF.value);
    }
    const valueData =(lits,item)=>{
        console.log(item,lits);
        let obj =JSON.parse(lits.Extend);
        console.log(obj[item],item);
        return  obj[item]
    }
    const elselect = (value,name,isEL,index)=>{
        if(isEL=='table'){
            let row = itemRefs.value[index].getCurrentRecord()
            row[name]=value
            // itemRefs.value[index].updateStatus(row)
        }else{
            list.value[name]=value
        }
        
    }
</script>
<style lang="scss" scoped>

</style>